import { DataSource, In } from 'typeorm';
import { Permission } from '@src/permission/entity/permission.entity';
import {
  ACTION_DESCRIPTION,
  RESOURCE_DESCRIPTION,
  P,
  PermissionCode,
} from '@src/common/const/permission.const';

function parseCode(code: string): { resource: string; action: string } {
  const [resource, action] = code.split(':', 2);
  return { resource, action };
}

export async function seedPermissions(dataSource: DataSource): Promise<void> {
  const repo = dataSource.getRepository(Permission);

  /* 常量定义的 code 集合 */
  const expectedCodes = new Set(Object.values(P));

  /* 数据库里已有的权限 */
  const existingPermissions = await repo.find();
  const existingCodes = new Set(existingPermissions.map((p) => p.code));

  /* 需要新增 / 删除的 */
  const toCreate: Partial<Permission>[] = [];
  for (const code of expectedCodes) {
    if (!existingCodes.has(code)) {
      const { resource, action } = parseCode(code);
      toCreate.push({
        code,
        resource,
        action,
        description: `允许 [${ACTION_DESCRIPTION[action]}] ${RESOURCE_DESCRIPTION[resource]}`,
      });
    }
  }

  const toDeleteCodes = existingPermissions
    .filter((p) => !expectedCodes.has(p.code as PermissionCode))
    .map((p) => p.code);

  await dataSource.transaction(async (em) => {
    const txRepo = em.getRepository(Permission);
    if (toCreate.length) {
      await txRepo.insert(toCreate);
    }
    if (toDeleteCodes.length) {
      await txRepo.delete({ code: In(toDeleteCodes) });
    }
  });
}
